# -*- coding: utf-8 -*-
"""
配置控制层

负责处理配置相关的HTTP请求和响应
"""
from fastapi import APIRouter, HTTPException, Depends, Request
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
from pydantic import BaseModel, Field
from typing import Optional, List, Dict, Any
from app.services.config_service import config_service
from app.controllers.user_controller import get_current_user

router = APIRouter(
    prefix="/admin/config",
    tags=["config"],
    responses={404: {"description": "Not found"}}
)

# HTTP Bearer token scheme
security = HTTPBearer()

# Pydantic 模型
class ConfigUpdateRequest(BaseModel):
    config_key: str = Field(..., description="配置键名")
    config_value: Any = Field(..., description="配置值")

class ConfigCreateRequest(BaseModel):
    config_key: str = Field(..., description="配置键名")
    config_value: str = Field(..., description="配置值")
    config_type: str = Field("string", description="配置类型")
    config_group: str = Field(..., description="配置分组")
    config_desc: Optional[str] = Field(None, description="配置描述")
    is_encrypted: bool = Field(False, description="是否加密")
    is_system: bool = Field(False, description="是否系统配置")

class BatchConfigUpdateRequest(BaseModel):
    configs: List[ConfigUpdateRequest] = Field(..., description="配置列表")


@router.get("/groups")
async def get_config_groups(current_user = Depends(get_current_user)):
    """获取所有配置分组"""
    try:
        grouped_configs = config_service.get_all_configs_by_group()
        return {
            "code": 200,
            "message": "获取成功",
            "data": grouped_configs
        }
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取配置分组失败: {str(e)}")


@router.get("/group/{group_name}")
async def get_config_by_group(group_name: str, current_user = Depends(get_current_user)):
    """根据分组获取配置"""
    try:
        configs = config_service.get_config_group(group_name)
        return {
            "code": 200,
            "message": "获取成功",
            "data": {
                "group_name": group_name,
                "configs": configs
            }
        }
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取配置失败: {str(e)}")


@router.get("/key/{config_key}")
async def get_config_by_key(config_key: str, current_user = Depends(get_current_user)):
    """根据键名获取配置"""
    try:
        config_value = config_service.get_config(config_key)
        
        if config_value is None:
            raise HTTPException(status_code=404, detail="配置不存在")
        
        return {
            "code": 200,
            "message": "获取成功",
            "data": {
                "config_key": config_key,
                "config_value": config_value
            }
        }
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取配置失败: {str(e)}")


@router.put("/update")
async def update_config(request: ConfigUpdateRequest, current_user = Depends(get_current_user)):
    """更新配置"""
    try:
        success = config_service.update_config(
            config_key=request.config_key,
            config_value=request.config_value,
            updated_by=current_user.get('user_id')
        )
        
        if success:
            return {
                "code": 200,
                "message": "配置更新成功"
            }
        else:
            raise HTTPException(status_code=400, detail="配置更新失败")
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"配置更新失败: {str(e)}")


@router.put("/batch-update")
async def batch_update_configs(request: BatchConfigUpdateRequest, current_user = Depends(get_current_user)):
    """批量更新配置"""
    try:
        configs = [
            {
                "config_key": config.config_key,
                "config_value": config.config_value
            }
            for config in request.configs
        ]
        
        success = config_service.batch_update_configs(
            configs=configs,
            updated_by=current_user.get('user_id')
        )
        
        if success:
            return {
                "code": 200,
                "message": f"批量更新 {len(configs)} 个配置成功"
            }
        else:
            raise HTTPException(status_code=400, detail="批量更新配置失败")
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"批量更新配置失败: {str(e)}")


@router.post("/create")
async def create_config(request: ConfigCreateRequest, current_user = Depends(get_current_user)):
    """创建新配置"""
    try:
        config_data = {
            "config_key": request.config_key,
            "config_value": request.config_value,
            "config_type": request.config_type,
            "config_group": request.config_group,
            "config_desc": request.config_desc,
            "is_encrypted": 1 if request.is_encrypted else 0,
            "is_system": 1 if request.is_system else 0,
            "created_by": current_user.get('user_id')
        }
        
        config_id = config_service.create_config(config_data)
        
        if config_id:
            return {
                "code": 200,
                "message": "配置创建成功",
                "data": {
                    "config_id": config_id,
                    "config_key": request.config_key
                }
            }
        else:
            raise HTTPException(status_code=400, detail="配置创建失败")
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"配置创建失败: {str(e)}")


@router.post("/refresh-cache")
async def refresh_cache(current_user = Depends(get_current_user)):
    """刷新配置缓存"""
    try:
        success = config_service.refresh_cache()
        
        if success:
            return {
                "code": 200,
                "message": "配置缓存刷新成功"
            }
        else:
            raise HTTPException(status_code=500, detail="配置缓存刷新失败")
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"配置缓存刷新失败: {str(e)}")


# 公开接口（不需要登录）
@router.get("/public/wechat")
async def get_public_wechat_config():
    """获取公开的微信配置（不包含敏感信息）"""
    try:
        wechat_config = config_service.get_wechat_config()
        
        # 只返回非敏感信息
        public_config = {
            "app_id": wechat_config.get('app_id', ''),
            "api_base": wechat_config.get('api_base', '')
        }
        
        return {
            "code": 200,
            "message": "获取成功",
            "data": public_config
        }
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取配置失败: {str(e)}")


@router.get("/public/business")
async def get_public_business_config():
    """获取公开的业务配置"""
    try:
        business_config = config_service.get_business_config()
        
        return {
            "code": 200,
            "message": "获取成功",
            "data": business_config
        }
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取配置失败: {str(e)}")


@router.post("/admin/wechat-config")
async def set_wechat_config(request: Request):
    """设置微信配置（管理员接口）"""
    try:
        body = await request.json()
        app_id = body.get('app_id')
        app_secret = body.get('app_secret')
        
        if not app_id or not app_secret:
            raise HTTPException(status_code=400, detail="app_id和app_secret不能为空")
        
        success = config_service.set_wechat_config(app_id, app_secret)
        
        if success:
            return {
                "code": 200,
                "message": "微信配置设置成功"
            }
        else:
            raise HTTPException(status_code=500, detail="配置设置失败")
            
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"设置配置失败: {str(e)}") 